<?php
namespace app\controller\app;

use app\BaseController;
use app\model\Customization;
use app\model\Message;
use app\model\Project;
use app\model\User;
use app\model\WorkOrderList;
use think\facade\Db;
use think\Request;

//use GuzzleHttp\Client;

//
class MyController extends BaseController
{
    //登录
    public function login(Request $request)
    {
        $authorization = $request->header('authorization');

        $psd = base64_encode($request->post('password'));
        $where = [
            'username' => $request->post('username'),
            'password' => $psd,
        ];
        $user = User::where($where)->find();

        if ($user) {
            if ($user->available == 0) {
                return fail(null, '已禁止登录');
            }
            $user->last_time = date('Y-m-d H:i:s', time());
            $user->save();
            $hidden = ['password', 'password_t', 'last_time', 'is_login', 'create_time', 'update_time', 'delete_time', 'have'];
            $user->hidden($hidden);
            // $token=base64_encode($request->post('username'));
            // Session::set($token, $user);
            // $user->token=$token;
            return success($user);
        } else {
            return fail(null, '账号或密码错误');
        }
    }
    //添加用户
    public function addUser(Request $request)
    {

        $user = new User;
        $data = $request->post();
        /* 身份添加判断 数组形式 */
        foreach ($data as $key => $value) {
            $user->$key = $value;
        }
        $user->password = base64_encode($request->post('password'));
        $user->password_t = $request->post('password');
        $user->special_customization = $request->post('special_customization');

        $rq = $user->save();
        if ($rq) {
            return success($data);
        }
    }
    public function updateUser(Request $request)
    {
        $user = User::find($request->post('id'));
        $data = $request->post();
        // Log::write($data, 'updateUser');
        if ($user) {
            foreach ($data as $key => $value) {
                $user->$key = $value;
            }
        }
        $rq = $user->save();
        if ($rq) {
            return success($data);
        }
    }
    public function delUser(Request $request)
    {
        $id = $request->post('id');
        $rq = User::destroy($id);
        if ($rq) {
            return success($request);
        }
    }
    //添加定制公司
    public function addCustomization(Request $request)
    {
        $data = $request->param();
        $id =$request->has('id','post');
        if($id){
            $customization = Customization::find($data['id']);
            if(!$customization){
                return fail(null,'不存在的ID');
            }
        }else{
            $customization = new Customization;
        }
        foreach ($data as $key => $value) {
            $customization->$key = $value;
        }
        $rq = $customization->save();
        if ($rq) {
            return success($data);
        }
    }
    // 定制公司列表
    public function customizationList(Request $request)
    {
        $Customization = Customization::select();
        $hidden = ['create_time', 'update_time', 'delete_time'];
        $Customization->hidden($hidden);
        return success($Customization);
    }
    // 添加MAC
    public function addMac(Request $request)
    {
        $equipmentType = $request->param('equipmentType');
        $request = $this->request->param();
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        unset($request['equipmentType']);
        foreach ($request as $key => $value) {
            $equipmentModel->$key = $value;
        }
        /* 判断是否存在该设备MAC */
        $exist = $equipmentModel::where('mac', $request['mac'])->find(); //最新的一条
        if ($exist) {
            return fail(null, '设备已存在');
        }
        /* eid生成 类型1位数+日期3位数+编号4位数 */
        //设备类型塔机:TowerCrane，升降机：Elevator，小车：TowerCar
        $array = [
            '1' => 'TowerCrane',
            '2' => 'Elevator',
            '3' => 'TowerCar',
            '4' => 'CraneCar',
        ];
        $time = substr(date('ym', time()), -3); //3位数日期
        $last_eq_eid = $equipmentModel::order('id desc')->value('eid'); //最新的一条
        $code = substr($last_eq_eid, -4); //编号5位数
        $eid = (array_search($equipmentType, $array) . $time . $code) + 1;
        $equipmentModel->eid = $eid;
        $equipmentModel->vcode = (string) mt_rand(1000, 9999); //生成四位数验证码--绑定
        $rq = $equipmentModel->save();
        return success($equipmentModel);
    }
    // 用户信息
    public function userInfo(Request $request)
    {
        $user = User::find($request->param('id'));
        $hidden = ['username', 'password', 'password_t', 'last_time', 'is_login', 'create_time', 'update_time', 'delete_time', 'have'];
        $user->hidden($hidden);
        return success($user);
    }
    // 用户信息
    public function userDetails(Request $request)
    {
        $where = [];
        $where[] = ['belong_user', 'find in set', $request->param('username')];
        $field = 'id,username,name,tel,company_name';
        $list = User::where('username', $request->param('username'))->find();
        $listProject = Project::where($where)->field('id,t102_num,t104_num,d101_num,s103_num,t105_num,t107_a2_num,t107_a2x_num')->select();
        if (!$listProject->isEmpty()) {
            foreach ($listProject as $key => $value) {
                $list['t102_num'] += $value->t102_num;
                $list['t104_num'] += $value->t104_num;
                $list['d101_num'] += $value->d101_num;
                $list['s103_num'] += $value->s103_num;
                $list['t105_num'] += $value->t105_num;
                $list['t107_a2_num'] += $value->t107_a2_num;
                $list['t107_a2x_num'] += $value->t107_a2x_num;
            }
        } else {
            $list['d101_num'] = 0;
            $list['t102_num'] = 0;
            $list['t104_num'] = 0;
            $list['t105_num'] = 0;
            $list['t107_a2_num'] = 0;
            $list['t107_a2x_num'] = 0;
            $list['s103_num'] = 0;
        }

        return success($list);

        // $list['TowerCrane'] = TowerCrane::where($where)->count();
        // $list['Elevator'] = Elevator::where($where)->count();
    }
    // 功能配置
    public function userConfig(Request $request)
    {
        $userConfig = [
            ['id' => 1, 'name' => '添加用户', 'grade' => 1],
            ['id' => 2, 'name' => '添加项目', 'grade' => 1],
            ['id' => 3, 'name' => '绑定设备', 'grade' => 1],
            ['id' => 4, 'name' => '参数下发', 'grade' => 1],
            ['id' => 5, 'name' => '设备功能修改', 'grade' => 1],
            // 1 => '添加用户',
            // 2 => '添加项目',
            // 3 => '绑定设备',
            // 4 => '参数下发',
            // 5 => '设备功能修改',
        ];
        return success($userConfig);
    }
    // 客户列表
    public function customerList(Request $request)
    {
        $where = [];
        $where[] = ['belong_user', 'find in set', $request->param('username')];
        $user = User::where($where)->field('id,name,tel,company_name,username')->select();
        return success($user);
    }
    // 设备列表-我的界面
    public function myEquipmentList(Request $request)
    {
        $where = [];
        if ($request->has('special_customization')) {
            $special_customization = $request->param('special_customization');
            $where[] = ['special_customization', '=', $special_customization];
        }else{
            $special_customization = 0;
        }
        //创建model
        $equipmentType = $request->param('equipmentType');
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        $dataType = ['TowerCrane', 'Elevator','TowerCar','CraneCar'];
        if (!in_array($equipmentType, $dataType)) {
            $EquipmentList['list'] = [];
            $EquipmentList['num']['sum'] = 0;
            $EquipmentList['num']['have'] = 0;
            $EquipmentList['num']['surplus'] = 0;
            return success($EquipmentList);
        }
        $EquipmentList['list'] = $equipmentModel::where($where)->order('create_time', 'desc')->field('eid,model,create_time,bind_time,pname,special_customization')->select();
        /* 定制数量 0探越 1王兴华 2安徽*/
        $mac_used = Db::name('mac_used')->field('type,sum')->select()->toArray();
        foreach ($mac_used as $key => $value) {
            $sum[$value['type']] = $value['sum'];
        }
        $EquipmentList['num']['sum'] = $sum[$special_customization];
        $EquipmentList['num']['have'] = $EquipmentList['list']->count();
        $EquipmentList['num']['surplus'] = $EquipmentList['num']['sum'] - $EquipmentList['num']['have'];
        // $dataType = ['TowerCrane', 'Elevator'];

        return success($EquipmentList);
    }
    //修改设备信息-我的界面
    public function updateEquipment(Request $request)
    {
        //创建model
        $equipmentType = $request->param('equipmentType');
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        $equipment = $equipmentModel::where('eid', $request->param('eid'))->find();
        $data = $request->post();
        unset($data['equipmentType']);
        if ($equipment) {
            foreach ($data as $key => $value) {
                $equipment->$key = $value;
            }
        }
        $rq = $equipment->save();
        //判断参数下发
        if ($this->request->has('issued_control')) {
            $ndataModelName = 'app\model\\' . $equipmentType . 'Ndata';
            $ndataModel = $ndataModelName::where('eid', $request['eid'])->find(); //最新一条数据
            $ndataModel->issued_control = $request->param('issued_control');
            $rq = $ndataModel->isAutoWriteTimestamp(false)->save();
        }
        if ($rq) {
            return success($rq);
        }
    }
    //添加mac数量
    public function addMacNum(Request $request)
    {
        $param = $request->param();
        $re = Db::table('mac_used')
            ->where('type', $param['type'])
            ->inc('sum', $param['sum'])
            ->update();
        return success($re);
    }
    //故障上报
    public function addBreakdown(Request $request)
    {
        $data = $request->param();
        $data['create_time'] = date("Y-m-d H:i:s", time());
        $re = Db::name('breakdown')->insert($data);
        return success($re);
    }
    //意见反馈
    public function addFeedback(Request $request)
    {
        $data = $request->param();
        $data['create_time'] = date("Y-m-d H:i:s", time());
        $re = Db::name('feedback')->insert($data);
        return success($re);
    }
    //故障上报列表
    public function breakdownList(Request $request)
    {
        $where = [];
        $where[] = ['belong_user', 'find in set', $request->param('username')];
        $re = Db::name('breakdown')->where($where)->order('id', 'desc')->select();
        return success($re);
    }
    //意见反馈列表
    public function feedbackList(Request $request)
    {
        $where = [];
        $where[] = ['belong_user', 'find in set', $request->param('username')];
        $re = Db::name('feedback')->where($where)->order('id', 'desc')->select();
        return success($re);
    }
    //修改密码
    public function updatePassword(Request $request)
    {
        $user = User::find($request->post('uid'));
        if ($request->post('old_psd') == $user->password_t) {
            $user->password = base64_encode($request->post('new_psd'));
            $user->password_t = $request->post('new_psd');
        } else {
            return fail(null, '原密码错误');
        }
        $rq = $user->save();
        if ($rq) {
            return success($rq);
        }
    }
    // 通知列表
    public function messageList(Request $request)
    {
        $uid = $request->param('uid');
        $re = Message::where('recipient', '=', $uid)->order('id', 'desc')->select();
        return success($re);
    }
    // 通知详情
    public function messageInfo(Request $request)
    {
        $message_id = $request->param('message_id');
        $message = Message::where('message_id', '=', $message_id)->find();
        $message->read = 1;
        $message->save();
        return success($message);
    }
    // 工单列表
    public function orderList(Request $request)
    {
        $where = [];
        $where[] = ['belong_user', 'find in set', $request->param('username')];
        $re = WorkOrderList::where($where)->order('examine_time', 'desc')->select();
        $group = $re->count();
        return success($re);
    }
    // 工单列表--单项目
    public function orderListP(Request $request)
    {
        $where = [];
        $where[] = ['pname', '=', $request->param('pname')];
        $re = WorkOrderList::where($where)->order('examine_time', 'desc')->select();
        return success($re);
    }
    //我的-未处理统计(故障,通知,反馈)
    public function unhandledList(Request $request)
    {
        $uid = $request->param('uid');
        $user = User::find($uid);
        $belong_user = $user->belong_user;
        $where = [];
        $where[] = ['belong_user', 'find in set', $belong_user];
        $where[] = ['processed', '=', 0];
        $list['info']['breakdown'] = Db::name('breakdown')->where($where)->order('id', 'desc')->find();
        $list['count']['breakdown'] = Db::name('breakdown')->where($where)->order('id', 'desc')->count();

        $list['info']['feedback'] = Db::name('feedback')->where($where)->order('id', 'desc')->find();
        $list['count']['feedback'] = Db::name('feedback')->where($where)->order('id', 'desc')->count();

        $list['info']['message'] = Message::where('recipient', '=', $uid)->where('read', 0)->order('id', 'desc')->find();
        $list['count']['message'] = Message::where('recipient', '=', $uid)->where('read', 0)->order('id', 'desc')->count();
        return success($list);
    }
    // 处理反馈意见
    public function handleFeedback(Request $request)
    {
        $id = $request->param('id');
        $opinion = $request->param('opinion');
        $opinion_peopleID = $request->param('opinion_peopleID');
        $opinion_tel = $request->param('opinion_tel');
        $opinion_name = $request->param('opinion_name');
        $re = Db::name('feedback')->save(['id' => $id, 'opinion' => $opinion, 'opinion_peopleID' => $opinion_peopleID, 'opinion_tel' => $opinion_tel, 'opinion_name' => $opinion_name, 'processed' => 1]);
        return success($re);
    }
    // 处理故障
    public function handleBreakdown(Request $request)
    {
        $id = $request->param('id');
        $opinion = $request->param('opinion');
        $opinion_peopleID = $request->param('opinion_peopleID');
        $opinion_tel = $request->param('opinion_tel');
        $opinion_name = $request->param('opinion_name');
        $re = Db::name('breakdown')->save(['id' => $id, 'opinion' => $opinion, 'opinion_peopleID' => $opinion_peopleID, 'opinion_tel' => $opinion_tel, 'opinion_name' => $opinion_name, 'processed' => 1]);
        return success($re);
    }
    // 轮播图
    public function banner(Request $request)
    {
        $list = Db::name('banner')->field('id,url')->select();
        return success($list);
    }
    //安卓远程软件下载地址
    public function getRangeUrl(Request $request)
    {
        $id = $request->param('id');
        $url = 'https://dl-customise.sunlogin.oray.com/sunlogin/customise/slrca/d/ddabedde6571ce29e797b987f9f41255/TenYirRemote.apk';
        if ($id == 1) {
            $url = 'http://video.sdtanyue.com/xrk.apk';//盘石
        }
        if ($id == 2) {
            $url = 'https://dl-customise.oray.com/sunlogin/customise/slrca/1/1fa6b52bf4551fadc69298f63c3debeb/RemoteControl.apk';//探越
        }
        return success($url);
    }
}
